import { DeleteOutlined, PauseOutlined, PlayCircleOutlined, SyncOutlined } from "@ant-design/icons"
import { Button, Input, Table } from "antd"
import { IDownloadDBTask } from "model/DB"
import moment from "moment"
import { useEffect } from "react"
import { useNavigate } from "react-router-dom"
import TabBtn from "renderer/components/TabBtn"
import TaskProgress from "renderer/components/TaskProgress"
import { TaskStatus } from "renderer/constants/Consts"
import useGlobal from "renderer/hooks/useGlobal"
import useTaskList from "renderer/hooks/useTaskList"
import { parseTime } from "renderer/utils/helps"
import './Download.less'

moment.locale('zh')

const { Search } = Input
const { Column } = Table

const PageSize = 20

let pollingTime: NodeJS.Timeout

export default function Download() {

  const navigate = useNavigate()

  const { playTask, playCourse, deleteCourse, pauseTask, resumeTask } = useGlobal()


  const { queryState, taskList, taskTotal, taskDispatch } = useTaskList({
    tab: 'downloading',
    name: '',
    page: 1,
    size: PageSize
  })



  // 一秒更新一次列表数据
  useEffect(() => {

    const pollingTask = () => {
      clearTimeout(pollingTime)

      // queryList()
      taskDispatch({type: 'update'})

      pollingTime = setTimeout(async() => {
        // console.log('update')
        taskDispatch({type: 'update'})
        pollingTask()
      }, 1000)
    }

    pollingTask()

  }, [])

  return (
    <div className="download-page" >
      <div className="download-header" >
        <div className="download-header-left">
          <Button type="link" className="back-btn" onClick={() => navigate("/home", {replace: true})} >返回</Button>
          <label className="download-label" >下载管理</label>
        </div>
        
        <Search className="download-search" placeholder='搜索课程名称' onSearch={(value) => taskDispatch({type: 'name', data: value}) }/>
      </div>
      <div className="download-content" >
        <div className="download-left" >
          <TabBtn select={queryState.tab === 'downloading'} onClick={() => taskDispatch({type: 'tab', data: 'downloading'}) }  >下载中</TabBtn>
          <TabBtn select={queryState.tab === 'completed'} onClick={() => taskDispatch({type: 'tab', data: 'completed'}) } >已完成</TabBtn>
        </div>
        <div className="download-right" >
          <Table className="download-table"
            dataSource={taskList}
            rowKey="id"
            pagination={{
              size: 'small',
              current: queryState.page,
              pageSize: PageSize,
              total: taskTotal,
              onChange: (page) => taskDispatch({type: 'page', data: page}) 
            }}
            scroll={{
              scrollToFirstRowOnChange: true,
              y: 'calc(100% - 42px)'
            }}
          >
            <Column title="课程名称" dataIndex="title" width={400}
              render={(_, record: IDownloadDBTask) => record.title + '-' + record.sub_title}
            />
            {queryState.tab === 'downloading' && <Column title="状态" dataIndex="status"  align="center" width={250}
              render={(_, record: IDownloadDBTask) => <TaskProgress percent={record.downloadCount/record.tsCount} status={record.status} />}
            />}
            {queryState.tab === 'completed' && <Column title="课程时长" dataIndex="duration" align="center" width={130}
              render={(_, record: IDownloadDBTask) => parseTime(record.duration)}
            />}
            {queryState.tab === 'completed' && <Column title="下载完成时间" dataIndex="completeTime" align="center" width={190} />}
            
            <Column title="操作" dataIndex="operate" align="center" width={100}
              render={(_, record: IDownloadDBTask) => queryState.tab === 'downloading' ? <>
                {(record.status === TaskStatus.Pause || record.status === TaskStatus.Error) && <Button type="link" title="继续下载"
                  // 继续下载
                  icon={<SyncOutlined />} 
                  onClick={async () => {
                    const result = await resumeTask(record)
                    taskDispatch({type: 'update'})
                  }}
                />}
                {(record.status === TaskStatus.Downloading || record.status === TaskStatus.Waiting) && <Button type="link" title="暂停"
                  // 暂停下载
                  icon={<PauseOutlined />}
                  onClick={async () => {
                    const result = await pauseTask(record)
                    taskDispatch({type: 'update'})
                  }}
                />}
                {(record.status === TaskStatus.Pause || record.status === TaskStatus.Error) && <Button type="link" title="删除"
                  // 删除下载任务
                  icon={<DeleteOutlined />} 
                  onClick={async () => {
                    // 删除课程
                    await deleteCourse(record)
                    // 更新列表
                    taskDispatch({type: 'update'})
                  }}
                />}
              </> : <>
                <Button type="link" title="播放"
                  icon={<PlayCircleOutlined />} 
                  onClick={() => {

                    playCourse({
                      taskId: record.id!,
                      url: record.url,
                      localUrl: record.localUrl,
                      title: record.title,
                      sub_title: record.sub_title,
                      path: record.path,
                      course_id: record.course_id,
                      sub_id: record.sub_id,
                      duration: record.duration,
                      playDate: moment().format('YYYY-MM-DD hh:mm:ss'),
                      playTime: 0,
                    })

                    // 跳转播放页
                    navigate("/home", {replace: true})
                  }}
                />
                <Button type="link" title="删除"
                  icon={<DeleteOutlined />} 
                  disabled={playTask?.id === record.id}
                  onClick={async () => {
                    // 删除课程
                    await deleteCourse(record)
                    // 更新列表
                    taskDispatch({type: 'update'})
                  }}
                />
            </>}
            />
          </Table>
        </div>
      </div>
    </div>
  )
}